package com.xwqiang.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

    /**
     * 跨域处理设置
     * @return
     */
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowCredentials(true);
        //设置访问原地址
        corsConfiguration.addAllowedOrigin("*");
        //设置访问源请求头
        corsConfiguration.addAllowedHeader("*");
        //设置请求方法
        corsConfiguration.addAllowedMethod("*");
        //设置有效期
        corsConfiguration.setMaxAge(3600L);
        //添加映射路径
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfiguration);
        //返回新的CorsFilter
        return new CorsFilter(source);
    }
}
